package org.his.controller.quanxian;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.his.dao.RoleDao;
import org.his.dao.UserDao;
import org.his.pojo.quanxuan.Role;
import org.his.pojo.quanxuan.User;
import org.his.utils.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.sql.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private UserDao userDao;

    @RequestMapping("/index")
    public String index() throws Exception{
        return "quanxian/user/index";
    }

    @RequestMapping("/form")
    public String form() throws Exception {
        return "quanxian/user/form";
    }
    @RequestMapping("/editform")
    public String editform() throws Exception {
        return "quanxian/user/editform";
    }

    @RequestMapping(value = "/add",method = RequestMethod.POST)
    @ResponseBody
//    @PostMapping("/add")
    public Map<String,Object> add(String roleid , Date birthdate,User user) throws Exception{
        Map<String,Object> map = new HashMap<>();
        user.setBirthdate(birthdate.toString());
        Md5Hash md5Hash = new Md5Hash(user.getPassword());
        user.setPassword(md5Hash.toString());


        userDao.add(user);
        userDao.addUserRole(user.getUserid(),Integer.parseInt(roleid));

        return map;
    }


    @RequestMapping(value = "/edit",method = RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> edit(String roleid , Date birthdate,User user) throws Exception{
        Map<String,Object> map = new HashMap<>();
        user.setBirthdate(birthdate.toString());
        Md5Hash md5Hash = new Md5Hash(user.getPassword());
        user.setPassword(md5Hash.toString());


        userDao.update(user);
        userDao.delUserRole(user.getUserid());
        userDao.addUserRole(user.getUserid(),Integer.parseInt(roleid));

        return map;
    }


    @InitBinder
    public void initBinder(WebDataBinder binder) throws Exception{
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        CustomDateEditor dateEditor = new CustomDateEditor(dateFormat,true);
        binder.registerCustomEditor(Date.class,dateEditor);
    }

    @RequestMapping("/touxiangadd")
    @ResponseBody
    public Map<String,Object> touxiangadd(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception{
        String pathRoot = request.getServletContext().getRealPath("/assets/images/user_touxiang");
        Map<String,Object> map = new HashMap<>();
        try {
            if(!file.isEmpty()){
                String filename = System.currentTimeMillis()+"_"+file.getOriginalFilename();//时间戳加源文件名
                File dest = new File(pathRoot + File.separator + filename);
                file.transferTo(dest);
                map.put("msg","ok");
                map.put("imgPath","assets/images/user_touxiang/"+filename);
            }
        } catch (IOException e) {
            e.printStackTrace();
            map.put("msg","error");
        } catch (IllegalStateException e) {
            e.printStackTrace();
            map.put("msg","error");
        }
        return map;
    }



    @RequestMapping("/list")
    @ResponseBody
    public Map<String,Object> list(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "5") Integer limit, User condition,String roleids) throws Exception{
        Map<String, Object> map = new HashMap<>();
        Page<User> pager = PageHelper.startPage(page, limit);
        if (roleids!= null && roleids != ""){
            Role role = new Role();
            role.setRoleid(Integer.parseInt(roleids));
            condition.setRole(role);
        }
        map.put("data", userDao.getList(condition));
        map.put("count", pager.getTotal());
        map.put("code", 0);
        map.put("msg", null);
        return map;
    }
    @RequestMapping("/batchDelete")
    @ResponseBody
    @RequiresPermissions("user:del")
    public Map<String,Object> batchDelete(Integer ids) throws Exception{
        Map<String,Object> map = new HashMap<>();
        userDao.delete(ids);
        return map;
    }

    @RequestMapping("/getUser")
    @ResponseBody
    public User getUser (Integer userid)throws Exception{
        return userDao.get(userid);
    }
}
